const router = require('@koa/router')();
const jwt = require('../utils/jwt.js')
const { findNoteListByType, finNoteDetailById, notePublish } = require('../controllers/index.js')
const { formateTime } = require('../utils/formateTime.js')

router.get('/findNoteListByType', jwt.verify(), async(ctx, next) => {
    // 检验Token合理再去数据库中查找数据返回给前端
    const { note_type } = ctx.request.query
    try {
        const res = await findNoteListByType(note_type, ctx.userId)
        if (res.length) {
            ctx.body = {
                code: '800',
                data: res,
                msg: '查询成功'
            }
        } else {
            ctx.body = {
                code: '800',
                data: res,
                msg: '当前分类下没有数据'
            }
        }
    } catch (error) {
        ctx.body = {
            code: '805',
            data: error,
            msg: '服务器异常'
        }
    }
})

router.get('/finNoteDetailById', jwt.verify(), async (ctx, next) => {
    // 检验Token合理再去数据库中查找数据返回给前端
    const { id } = ctx.request.query
    try {     
        const res = await finNoteDetailById(id)
        if (res.length) {
            ctx.body = {
                code: '800',
                data: res,
                msg: '查询成功'
            }
        } else {
            ctx.body = {
                code: '800',
                data: res,
                msg: '当前分类下没有数据'
            }
        }
    } catch (error) {
        ctx.body = {
            code: '805',
            data: error,
            msg: '服务器异常'
        }
    }
})

router.post('/note-publish', jwt.verify(), async(ctx) => {
    const {title, note_content, head_img, note_type} = ctx.request.body;
    const c_time = formateTime(new Date())
    const m_time = formateTime(new Date())
    
    try {
        const res = await notePublish({
            title, 
            note_content, 
            head_img, 
            note_type, 
            c_time, 
            m_time, 
            userId: ctx.userId, 
            nickname: ctx.nickname
        })
        if (res.affectedRows) {
            ctx.body = {
                code: '800',
                data: 'success',
                msg: '发布成功'
            }
        } else {
            ctx.body = {
                code: '804',
                data: 'fail',
                msg: '发布失败'
            }
        }
        // console.log(res);
    } catch (error) {
        ctx.body = {
            code: '805',
            data: error,
            msg: '服务器异常'
        }
    }
    
    // 往数据库写入

})
module.exports = router